# -*- coding: utf-8 -*-
# Author: qinxugao
# Date: 2017-08-28 16:27:01
#
# 重构项目的打包
import sys, csv , operator  
import os  
import glob  
import shutil
import subprocess
import traceback
import random
import fileinput
import encryptImg
import config

#num = random.randint(1,100)
#num = 74 #乐赢德州
num = 75	#高手德州
strTeakey = "xx"+ str(num) #加密密码
strTeasign = "xxsin"+ str(num)
tarPath = "/Users/qinxugao/work/Poker515_gs/" #高手德州扑克
scrPath = "/Users/qinxugao/work/Poker515"	#原515资源
curPath = os.getcwd()
upPath = os.path.dirname(tarPath)#取当前目录上一级目录



def mkdir(path):
    # 引入模块
    import os
    # 去除首位空格
    path=path.strip()
    # 去除尾部 \ 符号
    path=path.rstrip("\\")
    isExists=os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        print path+' 创建成功'
        # 创建目录操作函数
        os.makedirs(path)
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print path+' 目录已存在'
        return False
	

#make c++ file
def makeFile():
	content = '''
#ifndef __XXXXX_MyGrid3D_H__
#define __XXXXX_MyGrid3D_H__
#include "cocos2d.h"
using namespace cocos2d;
class  MyGrid3D : public CCNode 
{
public:
    MyGrid3D(){};
    ~MyGrid3D(){};

    void fun_blit(int a, int b){ int c=a-b;};
    void fun_reuse(int a, int b){ int c=a*b;};
    int  fun_xxx(int a, int b){return a+b;}
    int*   fun_getTexCoordinates(){return m_pTexCoordinates;}
    void   fun_setTexCoordinate(int* texCoord){m_pTexCoordinates = texCoord;}
    int*   fun_getVertices(){return m_pVertices;}
    void   fun_setVertices(int* texCoord){m_pVertices = texCoord;}
    void   fun_setGridRect(CCRect& rect){_gridRect=rect;}
    CCRect fun_getGridRect(){return _gridRect;}
    std::string fun_getString(){
    	string str = "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
    	str = str + "111111111111111111111111111111111111111111111111111111111111111111111111";
 		return str;   		
    }    
    static MyGrid3D* create(){
    	MyGrid3D *pRet = new MyGrid3D();
		if (pRet)
		{
			pRet->autorelease();
		}
		return pRet;
    }
protected:
    int *m_pTexCoordinates;
    int *m_pVertices;
    int *m_pOriginalVertices;
    int *m_pIndices;
	CCRect _gridRect;

};
#endif
		'''	
	tbFile = {}
	#随机名字
	a1 = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N']
	a2 = ['E','F','G','H']
	head = random.choice(a1) + random.choice(a2)+"Test"
	#文件夹列表
	for i in range(1,10):
		classList = []
		head = head + random.choice(a1)
		for j in range(1,1000):
			classList.insert(0,head+str(j))		
		tbFile["qxg"+str(i)] = classList


	oldClassName = "MyGrid3D"
	funcName = "fun_"
	
	for folder in tbFile:
		fol = upPath+"/sources/"+folder+"/"		
		if not os.path.exists(fol):
			os.makedirs(fol)
		else:
			#print("______clearPath___"+upPath+"/sources/rubbish")
			clearPath(fol)
		for name in tbFile[folder]:
			print(name)
			fp = open(fol+name+".h","w")			
			content2=content.replace(oldClassName,name)
			content2=content2.replace(funcName,funcName+str(random.randint(100,1000)))
			fp.write(content2)
			fp.close()

	changeFile(tbFile)
					
#修改文件
def changeFile(tbFile):
	lines = []
	includes = [
	'#include "cocos2d.h" //rubbish\n',
	'#include "AppDelegate.h" //rubbish\n',
	'#include "SimpleAudioEngine.h" //rubbish\n',
	'#include "support/CCNotificationCenter.h" //rubbish\n',
	'#include "CCLuaEngine.h" //rubbish\n',
	'#include <string>  //rubbish \n',
	'#include "MyLuaExtensions.h" //rubbish\n',
	'#include "pbc-lua.h" //rubbish\n',
	'#include "TalkingDataGA-Lua.h" //rubbish\n',
	'#include "cocos-ext.h"	//rubbish\n']

	#folderList = []
	FileList = []
	for folder in tbFile:
		#folderList.insert(0,folder)
		#print("folder"+folder)
		for fileName in tbFile[folder]:
			FileList.insert(0,fileName)
			includes.insert(0,'#include \"'+ folder+'/' + fileName+ '.h\" //rubbish\n')


	includes.insert(0,'#define XXTEAKEY \"'+ strTeakey +'\"  //rubbish\n')
	includes.insert(0,'#define XXTEASIGN \"'+ strTeasign +'\"  //rubbish\n')

	iDefLine = 0
	wline = 0
	#upPath = os.path.dirname(os.getcwd())#取当前目录上一级目录
	fileName = upPath + '/sources/AppRub.h'
	delLines = []
	createIndex = 0
	#if not os.path.exists(fileName):
	open(fileName,'w')
	with open(fileName, 'r') as f:
		lines = f.readlines()
		lineNum = 0
		for l in lines:
			if 'rubbish' in l:
				delLines.append(l)
			if 'applicationDidFinishLaunching' in l:
				createIndex = lineNum + 2
			lineNum = lineNum + 1

	for i in delLines:
		lines.remove(i)
		#print(i)
	for l in includes:
		lines.insert(wline,l)
		wline = wline + 1

	# lens = len(includes) + 1
	# if createIndex > 0:
	# 	lens = createIndex
	#print("___lens____",lens)
	lens = len(lines) + 1
	lines.insert(lens,'void createRubbish(){//rubbish \n')	
	index = 0
	for f in FileList:
		lens = len(lines) + 1
		lines.insert(lens,f+'::create();//rubbish \n')
		index = index + 1
		if index > 1000:
			break
	lens = len(lines) + 1			
	lines.insert(lens,'};//rubbish \n')
	with open(fileName, 'w') as f:
		for l in lines:			
				f.write(l)

	

def clearPath(top_path):
	for root, dirs, files in os.walk(top_path, topdown=False):
	    for name in files:
	        os.remove(os.path.join(root, name))
	    for name in dirs:
	        os.rmdir(os.path.join(root, name))	 

#src 原始目录， des 目标目录
def sourcecpy(src, des):
    src = os.path.normpath(src)
    des = os.path.normpath(des)
    #print(src,des)
    if not os.path.exists(src) or not os.path.exists(des):
        print("no path src")
        sys.exit(1)
    pathsrc, top = os.path.split(src) #路径 + 文件夹名   
    toplen = len(top)   
    for root, dirs, files in os.walk(src, topdown=True):  	
		for name in dirs:
			source = os.path.join(root, name)
			path, src_name = os.path.split(source) #取路径与名字			
			s = path[path.find(top)+toplen:]
			targetDir = des + s +"/"+ src_name			
			try:
				#print("____")
				shutil.copytree(source, targetDir)  #第一个参数是目录，第二个参数也是目录
			except OSError:
				print "______oserror shutil.copytree"
		for name in files:
			source = os.path.join(root, name)
			path, src_name = os.path.split(source) #取路径与名字
			s = path[path.find(top)+toplen:]			
			targetDir = des + s +"/"+ src_name			
			shutil.copy(source, targetDir)   #第一个参数是文件，第二个参数目录		

#加密lua文件
def encodeScript(key,sign):
	f=open("game.zip",'w')
	f.close()
	f=open("update.zip",'w')
	f.close()
	#cur = os.getcwd()
	gamezip = "game.zip"
	updatezip = "update.zip"
	cmdGame= "sh $QUICK_COCOS2DX_ROOT/bin/compile_scripts.sh -i "+ scrPath+"/scripts -o game.zip -e xxtea_zip -ek " +key+ " -es "+ sign
	cmdUpdate = "sh $QUICK_COCOS2DX_ROOT/bin/compile_scripts.sh -i "+ scrPath+"/update -o update.zip"
	#cmdRes = "sh $QUICK_COCOS2DX_ROOT/bin/pack_files.sh -i res -o resSec -ek "+key+" -es "+sign
	os.system(cmdGame)#在命令行上运行才有用
	os.system(cmdUpdate)
	#os.system(cmdRes)
	clearPath(upPath+"/scripts")	
	shutil.copy(gamezip, upPath+"/scripts")
	shutil.copy(updatezip, upPath+"/res")

#删除文件夹下除指定文件夹所有的文件
def deleteRes(src,folderName):    
    if not os.path.exists(src):
        print("no path src")
        sys.exit(1)
    pathsrc, top = os.path.split(src) #路径
    for root, dirs, files in os.walk(src, topdown=True):  	
		for name in dirs:
			source = os.path.join(root, name)
			#print(source)
			path, src_name = os.path.split(source) #取路径与名字			
			s = path[path.find(top)+len(top):]			
			if folderName == src_name:
				print("___folderName___"+folderName)			

#加密所有资源文件
def encodeRes(key,sign):
	resPath = upPath + "/res"
	clearPath(resPath)
	sourcecpy(scrPath+"/res",resPath)	
	#要删除的资源目录
	folderList = [resPath + "/ui/baijiale",
		resPath + "/ui/bairendezhou",
		resPath + "/ui/benchibaoma",
		resPath + "/ui/zhongfabai2",
		resPath + "/ui/roulette",
		resPath + "/ui/shuiguoji",
		resPath + "/ui/shuihu",
		resPath + "/ui/ponyrun",	
		resPath + "/ui/spellcardthree"
	]	
	for x in folderList:
		if os.path.exists(x):
			shutil.rmtree(x)
	if os.path.exists(resPath + "/update.zip"):
		os.remove(resPath + "/update.zip")	
	#加密所有资源文件
	encryptImg.encryptImgFile(resPath,key,sign)	

#往代码文件里加注释
def addNotes(path):
	for root , dirs, files in os.walk(path):
	        for name in files: 
	        	if  name.endswith(".cpp") or name.endswith(".c") or name.endswith(".h") or name.endswith(".m") or name.endswith(".mm"):#   
	        		lines = []
	        		filePath = os.path.join(root,name)  
	        		print(filePath)
	        		f = open(filePath, 'r')
	        		ls = f.readlines()
	        		for l in ls:
	        			if '\\' in l:
	        				lines.append(l)
	        				continue
	        			l = l + "////我欲乘风归去又恐琼楼玉宇高处不胜寒\n"
	        			lines.append(l)
					f.close()
					with open(filePath, 'w') as f:					
						for l in lines:			
							f.write(l)
#在.m文件中加入代码
def addRubbishToMM(path):
	for root , dirs, files in os.walk(path):
	        for name in files: 
	        	if name.endswith(".m") or name.endswith(".mm"):#   
	        		lines = []
	        		filePath = os.path.join(root,name)  
	        		print(filePath)
	        		f = open(filePath, 'r')
	        		ls = f.readlines()
	        		lineNum = 0
	        		for l in ls:
	        			if '\\' in l:
	        				lines.append(l)
	        				continue
	        			if '@end' in l:
	        				for n in range(1,100):
	        					lines.append('-(void)rubbish100'+str(n)+'{ \n')
	        					lines.append('for (int i = 0; i<10; i++) { \n')
	        					lines.append('NSLog(@"我欲乘风归去又恐琼楼玉宇高处不胜寒"); \n')
	        					lines.append('} \n')
	        					lines.append('NSLog(@"我欲乘风归去又恐琼楼玉宇高处不胜寒"); \n')
	        					lines.append('} \n')	        				        					        		
	        			lines.append(l)
					f.close()
					with open(filePath, 'w') as f:					
						for l in lines:			
							f.write(l)

#在.h文件中加入代码
def addRubbishToH(path):
	for root , dirs, files in os.walk(path):
	        for name in files: 
	        	if name.endswith(".h"):
	        		lines = []
	        		filePath = os.path.join(root,name)
	        		if name == 'AppRub.h' or ('qxg' in root):
	        			continue
	        		print(filePath)
	        		f = open(filePath, 'r')
	        		ls = f.readlines()
	        		lineNum = 0
	        		isStruct = False #是struct 不加入代码了
	        		lines.append('#include "stdio.h" \n')
	        		for l in ls:
	        			#print(l)
	        			if '\\' in l:
	        				print("------\\-----")
	        			elif 'class ' in l:
							isStruct = True
							#print("__isStruct = True__")													
	        			elif '};' in l:
	        				if isStruct == True:
	        					#print("_______",isStruct)     					
	        					isStruct = False
	        					for n in range(1,30):
	        						lines.append('void rubbishqq100'+str(n)+'(bool bValue){ printf("___qq__上帝保证过审______");}////___  \n') 	        							       					        		
	        			lines.append(l)
					f.close()
					with open(filePath, 'w') as f:					
						for l in lines:			
							f.write(l)									

# test
if __name__ == "__main__":
	#proPath = "/Users/qinxugao/work/projects/Poker_lua/proj.android"
	#要打包的android项目
	#proPath = raw_input('Please enter the filename:').strip()
	
	#读取配置
	num = 79
	tbCfg = config.getConfig(num)
	name = tbCfg['name']
	strTeakey = "xx"+ str(num) #加密密码
	strTeasign = "xxsin"+ str(num)
	tarPath = tbCfg['tarPath']
	scrPath = tbCfg['scrPath']
	upPath = os.path.dirname(tarPath)#取当前目录上一级目录		

	#增加垃圾文件
	#makeFile()	
	#修改.cpp
	#changeFile()
	#对代码文件加入无用注释
	path = tarPath+"/sources"
	#path = tarPath+"/proj.ios"
	path = upPath+'/test'
	#path = '/Users/qinxugao/work/Poker515_mj/sources/Extensions'
	path = '/Users/qinxugao/work/quick-cocos2d-x-2.2.6_m/lib/cocos2d-x/cocos2dx'
	#addNotes(path)
	#addRubbishToMM(path)
	addRubbishToH(path)
	#拷贝资源加密
	#encodeRes(strTeakey,strTeasign)
	#加密lua文件
	#encodeScript(strTeakey,strTeasign)



	




